package com.ruoyi.common.core.dsl

import ch.qos.logback.classic.boolex.IEvaluator
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.serializer.SerializerFeature
import org.slf4j.Logger
import org.slf4j.LoggerFactory

class AdapterContext {
    private static final Logger log = LoggerFactory.getLogger(AdapterContext.class);


    /**
     * 即adapterId
     */
    private String name
    /**
     * 全局变量
     */
    def global
    /**
     * 输入变量，为controller入参
     */
    def input
    /**
     * callApi时的RequestBody
     */
    def body


    /**
     * callApi后响应体，code为http code，body为响应string
     */
    def response = [:]
    /**
     * 数据库代理，使用db.${name}获取的为Ao对象
     */
    static Map<String, AdapterExecutor> executors
    static Map<String, IEvaluator> evaluators
    Map<String, AdapterRequest> api


    //给String添加asJSON、toJSONString和asXmlString方法
    static {
        String.metaClass.asJSON = { -> return JSON.parseObject(delegate as String) }
        Map.metaClass.toJSONString() { ->
            return JSON.toJSONString(delegate, SerializerFeature.DisableCircularReferenceDetect)
        }
        String.metaClass.asXmlString = { -> new XmlSlurper().parseText(delegate as String).text() }
    }


    /**
     * 抛出静默异常，此异常触发告警
     */
    def fail() {
        throw new Exception(name)
    }

    /**
     * 抛出静默异常，此异常触发告警
     * @param message 异常信息
     */
    def fail(String message) {
        throw new Exception(name, message)
    }


    /**
     * 调用其他adapter
     * @param adapterName适配器名称
     * @return 该adapter的执行结果
     */
    def require(String adapterName) {
        require(adapterName, input)
    }

    /**
     * 调用其他adapter
     * @param adapterName适配器名称
     * @param 指定入参 /上下文，调用的adapter都从input中取参数
     * @return 该adapter的执行结果
     */
    def require(String adapterName, Map<String, Object> customInput) {
        executors.get(adapterName).doAdapter(customInput)
    }

    def predict(String modelName, Map<String, Object> customInput) {
        evaluators.get(modelName).evaluate(customInput)
    }

    def predict(String modelName, Map<String, Object> customInput, List<String> featureNames) {
        evaluators.get(modelName).evaluate(customInput, featureNames)
    }


    def decryptWptCookie(String cookie) {
        try {
            if (cookie) {
                return WptCookie.decryptWptCookie(cookie)
            }
        } catch (Exception e) {
            log.warn("解cookie:{},失败", cookie, e)
        }
    }


}
